package com.cqupt.qualityevaluation.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqupt.qualityevaluation.common.Result;
import com.cqupt.qualityevaluation.dao.EvaluateSubmitFilesMapper;
import com.cqupt.qualityevaluation.dao.EvaluateSubmitMapper;
import com.cqupt.qualityevaluation.pojo.evaluatesubmit;
import com.cqupt.qualityevaluation.pojo.evaluatesubmitfiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    private EvaluateSubmitMapper evaluateSubmitMapper;
    @Autowired
    private EvaluateSubmitFilesMapper evaluateSubmitFilesMapper;

    @Value("${server.port}")
    private String port;
    private static final String ip = "http://localhost";

    /**
     * 删除文件
     * @param sPath 文件路径
     * @return 删除成功返回true，否则返回false
     */
    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 上传接口
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(MultipartFile[] files,String form) throws IOException {
        evaluatesubmit es = JSONObject.parseObject(form, evaluatesubmit.class); //JSON转为javaBean
//        System.out.println(es);
        // 处理重复提交
        QueryWrapper<evaluatesubmit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("schoolname",es.getSchoolname())
                .eq("evaluatetaskid",es.getEvaluatetaskid())
                .eq("evaluateindex3id",es.getEvaluateindex3id());
        evaluatesubmit repeatOne = evaluateSubmitMapper.selectOne(queryWrapper);
        if (repeatOne!=null){
//            System.out.println("重复了！！！");
            // 查询并删除文件
            QueryWrapper<evaluatesubmitfiles> queryWrapper1= new QueryWrapper<>();
            queryWrapper1.eq("submitid", repeatOne.getId());
            List<evaluatesubmitfiles> repeatFiles = evaluateSubmitFilesMapper.selectList(queryWrapper1);
            for (evaluatesubmitfiles repeatFile : repeatFiles) {
                deleteFile(repeatFile.getSubmitfilepath());
//                System.out.println("重复文件已删除"+repeatFile.getSubmitfilename());
            }

            evaluateSubmitMapper.deleteById(repeatOne.getId()); //删除重复项

        }
        // 提交到evaluateSubmit表中
        es.setSubmittime( new Timestamp(System.currentTimeMillis()) ); // 提交时间
        evaluateSubmitMapper.insert(es);



        long id = es.getId();// 提交的ID
        int n=0;
//        List<String> filePaths= new ArrayList<>(); // 上传文件列表
        Map<String, String> ff = new HashMap<>();// 上传文件列表 (原文件名：保存地址)
        if(files!=null)
        {
            for (MultipartFile file : files) {
                n++;
//                System.out.println("收到文件第"+n+"个"+file);
                String originalFilename = file.getOriginalFilename();//获取原文件名
                //定义文件唯一标识（前缀）
                String flag = IdUtil.fastSimpleUUID();
                long size = file.getSize();  // 文件大小(b)
                String rootFilePath = System.getProperty("user.dir").replace("\\","/")+"/QualityEvaluation/src/main/resources/files/"+flag+"_"+originalFilename;
                FileUtil.writeBytes(file.getBytes(), rootFilePath);// 把文件写入到上传的路径
                String fileUrl = ip+":"+port+"/files/"+flag;
                ff.put(originalFilename, fileUrl);
                evaluatesubmitfiles submitfile = new evaluatesubmitfiles();
                submitfile.setSubmitid((int) id);
                submitfile.setSubmitfilename(originalFilename);
                submitfile.setSubmitfilepath(rootFilePath);
                submitfile.setSubmitfilesize((int) (size/1024)); // 单位KB
                submitfile.setSubmitfilememo(fileUrl); // 文件下载链接

                evaluateSubmitFilesMapper.insert(submitfile);
            }
            System.out.println(ff);
        }


//        return ip+":"+port+"/files/"+flag; // 返回结果 url
        return "success";
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os; //新建输出流对象
        String basePath = System.getProperty("user.dir") + "/QualityEvaluation/src/main/resources/files/"; //定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath); //获取所有的文件名称
        String fileName = fileNames.stream().filter(name->name.contains(flag)).findAny().orElse("");// 找到参数一致的文件
        try{
            if(StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath+fileName); // 通过文件的路径读取文件字节流
                os = response.getOutputStream(); // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }

        }catch (Exception e){
            System.out.println("下载文件失败");
        }
    }
}
